<template>
	<view>
		<view class="popup_group">
			<view class="popup_group_item">
				<view class="popup_group_item_label">比赛名称</view>
				<view class="popup_group_item_value"><input v-model="setFormData.store_name" type="text" maxlength="32" value="" placeholder="比赛名称" /></view>
			</view>
			
			<view class="popup_group_item">
				<view class="popup_group_item_label">报名开始日期</view>
				<view class="popup_group_item_value">
					<!-- <picker mode="date" :start="setFormData.signFromDate" :value="setFormData.signFromDate" @change="onSignFromDateChange">
						<view class="uni-input">{{setFormData.signFromDate}}</view>
					</picker> -->
					<picker mode="date" :start="new Date().format('yyyy-MM-dd')" :value="setFormData.signFromDate" @change="onSignFromDateChange">
						<view class="uni-input">{{setFormData.signFromDate}}</view>
					</picker>
				</view>
			</view>
			
			<view class="popup_group_item">
				<view class="popup_group_item_label">报名结束日期</view>
				<view class="popup_group_item_value">
					<!-- <picker mode="date" :start="setFormData.signToDate" :value="setFormData.signToDate" @change="onSignToDateChange">
						<view class="uni-input">{{setFormData.signToDate}}</view>
					</picker> -->
					<picker mode="date" :start="new Date().format('yyyy-MM-dd')" :value="setFormData.signToDate" @change="onSignToDateChange">
						<view class="uni-input">{{setFormData.signToDate}}</view>
					</picker>
				</view>
			</view>
			
			<view class="popup_group_item">
				<view class="popup_group_item_label">比赛日期</view>
				<view class="popup_group_item_value">
					<!-- <picker mode="date" :start="setFormData.raceDate" :value="setFormData.raceDate" @change="onRaceDateChange">
						<view class="uni-input">{{setFormData.raceDate}}</view>
					</picker> -->
					<picker mode="date" :start="new Date().format('yyyy-MM-dd')" :value="setFormData.raceDate" @change="onRaceDateChange">
						<view class="uni-input">{{setFormData.raceDate}}</view>
					</picker>
				</view>
			</view>
			
			<view class="popup_group_item">
				<view class="popup_group_item_label">比赛钓场</view>
				<view class="popup_group_item_value">
					<!-- disabled="scene==2" 只有创建时才能指定钓场, 修改时不能改钓场, 商品所属的商家不能改 -->
					<picker :range="myServiceMers" range-key="merName" :value="currMerIdx" :disabled="scene==2" @change="onSelectMerchant">
						<view class="uni-input">{{myServiceMers[currMerIdx].merName}} <text class='iconfont icon-jiantou mg-l-sm'></text></view>
					</picker>
				</view>
			</view>
			
			<view class="popup_group_item">
				<view class="popup_group_item_label">价格（元）</view>
				<view class="popup_group_item_value"><input v-model="setFormData.yearlyYpPrice" type="digit" maxlength="5" placeholder="比赛价格" /></view>
			</view>
			
			<view class="popup_group_item">
				<view class="popup_group_item_label">人数</view>
				<view class="popup_group_item_value"><input v-model="setFormData.yearlyYpStock" type="number" maxlength="5" placeholder="比赛人数" /></view>
			</view>
			
		</view>
		
		<view class="input_content">
			<view class="input_content_describe" style="border-top: 0px;">
				<view class="input_content_describe_title">
					<view class="input_content_describe_title_msg">比赛章程</view>
					<view class="input_content_describe_title_num">
						<text v-if="setFormData.content">{{ setFormData.content.length }}</text>
						<text v-else>0</text>
						/2000
					</view>
				</view>
				<view class="input_content_describe_textarea" style="height: 300px;">
					<textarea style="height: 280px;" v-model="setFormData.content" value="" placeholder="请填写比赛章程" placeholderClass="placeholderClass" maxlength="2000" />
				</view>
			</view>
			
			<view class="photo_count">
				<text class="photo_size">添加主图和轮播图，第1张作为主图。建议：图片尺寸为750*750px</text>
				<view class="input_content_photo">
					<view class="input_content_photo_adPh" v-for="(item, index) in setFormData.imageList" :key="index">				
						<image :src="item" class="myimg2 photos"></image>  			
						<view class="input_content_photo_adPh_jiao" @click="deleteImage(index)"><image src="./static/images/close.png" mode=""></image></view>
					</view>
					<view v-if="setFormData.imageList.length < 9" class="input_content_photo_adPh addBtn" @click="clk">
						<view><image src="./static/images/creamer.png" mode="widthFix"></image></view>
						<view>添加图片</view>
					</view>
				</view>
			</view>
		</view>	
		
		<view class="handle dobuButton">
			<view class="handle_button" @click="doSubmit">{{scene==1?'发布比赛':(scene==2?'保存修改':'重新发布比赛')}}</view>
		</view>

		<avatar @upload="doUpload" quality="1" ref="avatar" selWidth="250upx" selHeight="250upx"></avatar>
	</view>
</template>

<script>
	const app = getApp();
	
	import { navigateTo, serialize, setStorage, getStorage, removeStorage, Loading, hideLoading, Modal } from '@/libs/uniApi.js';
	import {MyTip} from '@/components/ssty/common.js';
	
	import { productCreate, productUpdate, productDetail } from '@/api/product.js';
	import { getMyServiceMerchants, getRaceCateId, getRaceById, queryRaces } from '@/api/fsh.js';

	import {TOKENNAME, HTTP_REQUEST_URL} from '@/config/app.js';
	import store from '@/store';
	import avatar from "@/components/yq-avatar/yq-avatar.vue";

	export default {
		components: {
			avatar
		},

		data() {
			return {
				scene: 1,
				myServiceMers: [],
				currMerIdx: 0,
				
				setFormData: {					
					store_name: '', // 商品名
					signFromDate: new Date().format('yyyy-MM-dd'), 	// 报名开始日期（时间默认为00:00:00开始）
					signToDate: new Date().format('yyyy-MM-dd'), 	// 报名结束日期（时间默认为23:59:59结束）
					raceDate: new Date().format('yyyy-MM-dd'), 		// 比赛日期（时间根据钓塘的固定时间段配置走）
					yearlyYpPrice: undefined, // 价格
					yearlyYpStock: undefined, // 比赛人数
					
					store_info: '比赛',
					content: '', // 比赛详情
					
					imageList: [],
					image: '', //主图
					slider_image: '', // 轮播图
				}
			}
		},
		watch: {
			setFormData: {
				handler(val) {
					console.log("watch setFormData:", JSON.stringify(val));
					if(this.scene != 3) {
						setTimeout(()=>{
							setStorage(this.scene==1 ? 'addRaceFormData' : 'editRaceFormData', this.setFormData);
						});
					}
				},
				deep: true
			},
			'setFormData.imageList'(val) {
				this.setFormData.image = val.length ? val[0] : '';
				this.setFormData.slider_image = val.length ? serialize(val).splice(1) : [];
			}
		},
		onLoad(options) {
			this.scene = parseInt(options.scene);
			this.raceId = parseInt(options.raceId);
			this.prodId = parseInt(options.prodId);
			this.merId = parseInt(options.merId);
			
			console.log(`race_manage_edit_info::onLoad, scene=${this.scene}, raceId=${this.raceId}, options:`, options);
			
			let reqs = [];
			reqs.push(this.loadMyMerchants());
			if(this.scene == 1) {
				uni.setNavigationBarTitle({
					title: '发布比赛'
				})
				this.loadDataFromStorage();
			}
			else {
				reqs.push(this.loadDataFromSrv());
				uni.setNavigationBarTitle({
					title: this.scene == 2?'修改比赛':'重新发布比赛'
				})
			}
			
			if(!app.globalData.race_cate) {
				reqs.push(this.loadRaceCate());
			}
			console.log("app.globalData.race_cate="+app.globalData.race_cate);
			
			if(reqs.length > 1) {
				Promise.all(reqs).then(res=>{}).catch(err=>{
					Modal('网络请求失败', '请稍后重试', {
						showCancel: false,
					}).then(() => {
						uni.navigateBack();
					})
				})
			}
		},
		methods: {
			// 从cache获取数据
			async loadDataFromStorage() {
				if (getStorage('addRaceFormData')) {
					this.setFormData = getStorage('addRaceFormData');
				}
			},
			
			// 查询详情数据
			loadDataFromSrv() {
				Loading();
				
				removeStorage('editRaceFormData'); 

				return productDetail(this.merId, this.prodId).then(res => {
					hideLoading();
					
					setStorage('editRaceFormData', res.data);
					
					Object.keys(this.setFormData).forEach(item => {
						this.setFormData[item] = res.data[item];
					});
					this.setFormData.product_id = this.prodId;
					this.setFormData.imageList = [...(this.setFormData.image ? [this.setFormData.image] : []), ...this.setFormData.slider_image];
					
					this.setFormData.yearlyYpPrice = parseFloat(res.data.yp.price);
					this.setFormData.yearlyYpStock = parseInt(res.data.stock);
					let pos = res.data.yp.sign_from_time.indexOf(" ");
					this.setFormData.signFromDate = res.data.yp.sign_from_time.substr(0, pos);
					pos = res.data.yp.sign_to_time.indexOf(" ");
					this.setFormData.signToDate = res.data.yp.sign_to_time.substr(0, pos);
					this.setFormData.raceDate = res.data.yp.race_date;
				}).catch(e => {
					hideLoading();
					MyTip('加载失败，请稍后重试');
				});
			
			},
			
			loadMyMerchants(showLoading) {
				if(showLoading)
					uni.showLoading({
						title: "获取钓场..."
					});
				return getMyServiceMerchants().then(res=>{
					console.log(res.entity)
					this.myServiceMers = res.entity;
					for(let i = 0; i < res.entity.length; i++) {
						console.log(res.entity[i].merId)
					}
					if(this.scene != 1) {
						for(let i = 0; i < res.entity.length; i++) {
							if(res.entity[i].merId == this.merId) {
								this.currMerIdx = i;
								break;
							}
						}
					}
					if(showLoading)
						uni.hideLoading();
				}).catch(err=>{
					if(showLoading) {
						Modal('获取钓场失败', '请联系钓场管理员', {
							showCancel: false,
						}).then(() => {
							uni.navigateBack();
						})
					}
				})
			},
			
			loadRaceCate(showLoading) {
				if(showLoading)
					uni.showLoading({
						title: "获取比赛分类ID..."
					});
				return getRaceCateId().then(res=>{
					app.globalData.race_cate = res.entity;
					if(showLoading)
						uni.hideLoading();
				}).catch(err=>{
					if(showLoading) {
						Modal('获取比赛分类ID失败', '请稍后重试', {
							showCancel: false,
						}).then(() => {
							uni.navigateBack();
						})
						uni.hideLoading();
					}
				})
			},
			
			onSelectMerchant(e) {
				this.currMerIdx = e.detail.value;
			},
			
			onSignFromDateChange(e) {
				this.setFormData.signFromDate = e.detail.value
			}, 
			
			onSignToDateChange(e) {
				this.setFormData.signToDate = e.detail.value
			},
			
			onRaceDateChange(e) {
				this.setFormData.raceDate = e.detail.value
			},

			clk() {
				let avatar = this.$refs.avatar;
				avatar.fChooseImg(1,{selWidth: '350upx', selHeight: '350upx', inner: true});
			},
			doUpload(rsp) {
				let that = this
				console.log(rsp);	
				
			
				uni.uploadFile({
					url: HTTP_REQUEST_URL + '/api/upload/image/field',
					filePath: rsp.path,
					name: 'field',
					formData: {
						'filename': rsp.path
					},
					header: {
						// #ifdef MP
						"Content-Type": "mulMyTipart/form-data",
						// #endif
						[TOKENNAME]: 'Bearer ' + store.state.app.token
					},
					success: (uploadFileRes) => {
						console.log(uploadFileRes.data);
						let imgData = JSON.parse(uploadFileRes.data)
						that.setFormData.imageList.push(imgData.data.path)
					},
					complete(res) {
						console.log(res)
					}
				});		
			},
			// 删除图片
			deleteImage(index) {
				this.setFormData.imageList.splice(index, 1);
			},
			
			checkForm() {
				let requireData = {
					// image: '请选择主图', 
					store_name: '请输入比赛名称',
					yearlyYpPrice: '请输入价格',
					yearlyYpStock: '请输入比赛人数', // 比赛人数可以 > (分区人数x分区)，比如100人的比赛允许120人报名，然后审核pass掉20个
					signFromDate: '请输入报名开始日期',
					signToDate: '请输入报名结束日期',
					raceDate: '请输入比赛日期',
					// store_info: '请输入比赛介绍',
					content: '请输入比赛章程'
				};
				if(Object.keys(requireData).some(item => {
					if (!this.setFormData[item]) {
						MyTip(requireData[item]);
						return true;
					}
				}))
					return false;
				return true;
			},
			
			// 发布比赛
			doSubmit() {
				if(!this.checkForm())return;
				let postData = {
					...this.setFormData,
					cate_id: app.globalData.race_cate,
				};
				let raceUseMerId = this.myServiceMers[this.currMerIdx].merId;
				
				console.log(`race_manage_edit_info::doSubmit ..., scene=${this.scene}, raceUseMerId=${raceUseMerId}, postData:`, postData);
				
				switch(this.scene)
				{
					case 1:
					case 3: {
						uni.showLoading({
							title: '正在创建中...'
						});

						productCreate(raceUseMerId, postData).then(res => {
							hideLoading();
							
							let raceId = parseInt(res.message);
							console.log(`race_manage_edit_info::doSubmit| productCreate success, raceId=${raceId}`);
							
							removeStorage("addRaceFormData"); // 清除新建缓存
							
							queryRaces(3, 1, 1, raceId).then(res => {
								Modal('发布成功', '点击确定，进入赛事管理', {
									showCancel: false,
								}).then(() => {
									let race = res.entity.list[0];
									app.globalData.tempParam_for_raceManage = race;
									uni.switchTab({
										url:`/pages/fsh_race_main/race_main`,
										success:()=>{
											uni.navigateTo({
												url:`/pages/fsh_race/race_manage?raceName=${this.setFormData.store_name}&raceId=${raceId}&merId=${raceUseMerId}&prodId=${race.prodId}`
											})	
										}
									})									
								})
							}).catch(err => {
							});
						})
						.catch(errMsg => {
							hideLoading();
							console.log("race_manage_edit_info::doSubmit| productCreate false", errMsg);
							MyTip(errMsg);
						});
							
						break;
					}
					case 2: {
						uni.showLoading({
							title: '正在修改中...'
						});

						productUpdate(this.merId, this.setFormData.product_id, postData)
							.then(res => {
								hideLoading()
								
								console.log("race_manage_edit_info::doSubmit| productCreate success");
								removeStorage("editRaceFormData");
								
								Modal('修改成功', '', {
									showCancel: false
								}).then(() => {
									uni.navigateBack();
								})
							})
							.catch(errMsg => {
								uni.hideLoading();
								console.log("ypIndex::doSubmit| productUpdate fail", errMsg);
								MyTip(errMsg);
							});
					}
				}
			}
			
		}
	}
</script>

<style lang="scss" scoped>
	@import "@/leui.scss";
	
	page {
		height: 100%;
		background-color: #f5f5f5;
	}
	
	
	.popup_group {
		background: #fff;
		margin: 31rpx auto;
		width: 710rpx;
		font-size: 30rpx;
		border-radius: 10rpx;
		.popup_group_item {
			padding: 32rpx 30rpx;
			display: flex;
			align-items: center;
			justify-content: space-between;
			.popup_group_item_value {
				display: flex;
				align-items: center;
				.popup_group_item_message {
					margin-right: 15rpx;
					color: #bbbbbb;
					max-width: 400rpx;
					&_value {
						color: #000;
					}
				}
				.iconfont {
					color: #bbbbbb;
				}
				input {
					text-align: right;
				}
			}
		}
		> view:not(:last-child) {
			border-bottom: 1px solid #eeeeee;
		}
	}
	
	.input_content {
		background: #fff;
		padding: 20rpx 30rpx 40rpx 30rpx;
		width: 710rpx;
		margin: auto;
		box-sizing: border-box;
		border-radius: 10rpx;
		&_textarea {
			border-bottom: 1px solid #eeeeee;
			padding-bottom: 19rpx;
			textarea {
				height: 114rpx;
			}
			> view {
				text-align: right;
				color: #666666;
				font-size: 24rpx;
			}
		}
	
		&_photo {
			margin-top: 30rpx;
			display: flex;
			flex-wrap: wrap;
			
			&_adPh {
				position: relative;
				width: 210rpx;
				height: 210rpx;
				border: 1px solid #dddddd;
				display: flex;
				flex-direction: column;
				justify-content: center;
				border-radius: 8rpx;
				margin-right: 10rpx;
				margin-bottom: 10rpx;
				box-sizing: border-box;
				&:nth-child(3n){
					margin-right: 0;
				}
				> view:nth-child(1) {
					height: 37rpx;
					margin-bottom: 16rpx;
					display: flex;
					justify-content: center;
					image {
						width: 45rpx;
						display: block;
					}
				}
	
				> view:nth-child(2) {
					text-align: center;
					color: #bbbbbb;
					font-size: 24rpx;
				}
				.photos {
					width: 206rpx;
					// height: 208rpx;
				}
				&_jiao {
					position: absolute;
					top: -2rpx;
					right: -1rpx;
					width: 40rpx;
					height: 40rpx;
					background: rgba(0,0,0,.6);
					display: flex;
					align-items: center;
					justify-content: center;
					border-radius: 0 8rpx 0 8rpx;
					image {
						width: 16rpx;
						height: 16rpx;
					}
				}
			}
		}
		&_describe {
			border-top: 1px solid #eeeeee;
			padding-top: 30rpx;
			padding-bottom: 47rpx;
			border-bottom: 1px solid #eeeeee;
			&_title {
				display: flex;
				align-items: center;
				justify-content: space-between;
				&_msg {
					color: #333333;
					font-size: 30rpx;
				}
				&_num {
					color: #666666;
					font-size: 24rpx;
				}
			}
	
			&_textarea {
				border-radius: 10px;
				margin-top: 20rpx;
				height: 180rpx;
				background: #f5f5f5;
				padding: 20rpx;
				textarea {
					font-size: 28rpx;
					height: 150rpx;
				}
			}
		}
	
		&_keyword {
			padding-top: 32rpx;
			display: flex;
			align-items: center;
			justify-content: space-between;
			font-size: 30rpx;
			&_value {
				flex: 1;
				margin-left: 30rpx;
				input {
					width: 100%;
					text-align: right;
				}
			}
		}
	}
	
	.photo_count{
		margin-top: 28rpx;
		.photo_size{
			font-size: 24rpx;
			color: #999999;
		}
	}
	
	.dobuButton {
		padding: 0 30rpx;
	}
	
	
	.handle {
		width: 100%;
		height: 126rpx;
		background: #ffffff;
		display: flex;
		align-items: center;
		justify-content: center;
		position: fixed;
		left: 0;
		bottom: 0;
		z-index: 10;
		&_button {
			width: 690rpx;
			height: 86rpx;
			background: #e93323;
			border-radius: 43px;
			display: flex;
			align-items: center;
			justify-content: center;
			font-size: 32rpx;
			color: #ffffff;
		}
	}
</style>
